package cn.serenedream.housedecoration.dao;

import cn.serenedream.housedecoration.entity.Sale;
import cn.serenedream.housedecoration.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface SaleRepository extends JpaRepository<Sale, Long> {
    @Query(
            value = "SELECT * FROM sale s JOIN user u ON s.user_id = u.id WHERE u.name LIKE CONCAT('%', :name, '%')",
            nativeQuery = true
    )
    Page<Sale> findByName(Pageable pageable, @Param("name") String name);

    @Modifying
    @Transactional // 必须加事务！
    @Query(value = """
    INSERT INTO sale (id, user_id, price, create_date) 
    VALUES (:#{#sale.id}, :#{#sale.user.id}, :#{#sale.price}, :#{#sale.createDate})
    """, nativeQuery = true)
    void insert(@Param("sale") Sale sale);

    @Modifying
    @Query(value = "delete from sale where id = :id", nativeQuery = true)
    void deleteBySaleId(@Param("id") String id);

    @Query(value = "select `user_id` from sale where `id` = :id", nativeQuery = true)
    Long findUserById(@Param("id") String id);

    Page<Sale> findByUser_NameContaining(String name, Pageable pageable);
}
